package com.mjh.zhujianju.controller.agency;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.livew.framework.base.controller.BaseController;
import com.livew.framework.base.service.BaseService;
import com.livew.framework.enums.EUserRoleType;
import com.livew.framework.exception.XTBusinessException;
import com.livew.framework.page.PagedResult;
import com.livew.framework.pojo.AjaxResult;
import com.livew.framework.utils.XTListUtils;
import com.mjh.zhujianju.excel.ExcelUtil;
import com.mjh.zhujianju.model.base.UserExtendEO;
import com.mjh.zhujianju.service.agency.DeptUserService;
import com.mjh.zhujianju.service.base.UserExtendService;
import com.mjh.zhujianju.vo.agency.DeptUserVO;
import com.mjh.zhujianju.vo.base.SysUserVO;

@Controller("UserExtController")
@RequestMapping("agency/user")
public class UserController extends BaseController<UserExtendEO> {

	@Resource
	private UserExtendService userExtendService;

	@Resource
	private DeptUserService deptUserService;

	@Override
	protected BaseService<UserExtendEO> getService() {

		return userExtendService;
	}

	/**
	 * 获取所有的用户
	 * 
	 * @Description:
	 * @return
	 * @author wt1293
	 * @date 2018年8月9日下午8:08:53
	 *
	 */
	@RequestMapping(value = "getPage", method = RequestMethod.POST)
	@ResponseBody
	public AjaxResult getPage(SysUserVO vo) {
		vo.setType(EUserRoleType.user.getCode());
		vo.setUserId(vo.getDeptId());
		PagedResult<SysUserVO> list = userExtendService.getVOList(vo);
		return AjaxResult.getResult(list);
	}

	/**
	 * 获取部门下所有的用户
	 *
	 * @Description:
	 * @return
	 * @author wt1293
	 * @date 2018年8月9日下午8:08:53
	 *
	 */
	@RequestMapping(value = "getUserPage", method = RequestMethod.POST)
	@ResponseBody
	public AjaxResult getUserPage(@RequestBody SysUserVO vo) {
		PagedResult<SysUserVO> list = userExtendService.getUserList(vo);
		return AjaxResult.getResult(list);
	}

	/**
	 * 保存信息
	 * 
	 * @param vo
	 * @return
	 */
	@RequestMapping(value = "saveInfo", method = RequestMethod.POST)
	@ResponseBody
	public AjaxResult saveInfo(SysUserVO vo) {
		if (vo == null) {
			return AjaxResult.getResult(Boolean.FALSE, "参数错误");
		}
		try {
			vo.setType(EUserRoleType.user.getCode());
			userExtendService.saveInfo(vo);
		} catch (XTBusinessException e) {
			e.printStackTrace();
			return AjaxResult.getResult(Boolean.FALSE, e.getMessage());
		}
		return AjaxResult.getResult(Boolean.TRUE, "保存成功");
	}

	
	/**
	 * 保存信息
	 * 
	 * @param vo
	 * @return
	 */
	@RequestMapping(value = "updateInfo", method = RequestMethod.POST)
	@ResponseBody
	public AjaxResult updateInfo(SysUserVO vo) {
		if (vo == null) {
			return AjaxResult.getResult(Boolean.FALSE, "参数错误");
		}
		try {
			userExtendService.updateInfo(vo);
		} catch (XTBusinessException e) {
			e.printStackTrace();
			return AjaxResult.getResult(Boolean.FALSE, e.getMessage());
		}
		return AjaxResult.getResult(Boolean.TRUE, "保存成功");
	}

	/**
	 * 重新获取详情
	 */
	public AjaxResult findById(@PathVariable("id") Long id) {
		if (id == null) {
			return AjaxResult.getResult(Boolean.FALSE, "参数错误");
		}
		SysUserVO t = null;
		try {
			t = this.userExtendService.getInfo(id);
		} catch (XTBusinessException e) {
			e.printStackTrace();
			return AjaxResult.getResult(Boolean.FALSE, e.getMessage());
		}
		return AjaxResult.getResult(t);
	}

	/**
	 * 重新获取详情
	 */
	@RequestMapping(value = "findByDeptId/{id}", method = RequestMethod.GET)
	@ResponseBody
	public AjaxResult findByDeptId(@PathVariable("id") Long id) {
		if (id == null) {
			return AjaxResult.getResult(Boolean.FALSE, "参数错误");
		}
		List<DeptUserVO> t = deptUserService.queryDeptListByDeptId(id);
		return AjaxResult.getResult(t);
	}

	
	/**
	 * 导出工作人员信息
	 * @param deptId
	 * @param remark2
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "exportExcel", method = RequestMethod.GET)
	public void exportExcel(Long deptId, String remark2, HttpServletResponse response) throws IOException {
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet("信息表");
		SysUserVO vo = new SysUserVO();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String time = sdf.format(new Date());
		vo.setType(EUserRoleType.user.getCode());
		vo.setRemark2(remark2);
		vo.setUserId(deptId);
		PagedResult<SysUserVO> list = userExtendService.getVOList(vo);
		String fileName = "工作人员" + time + ".xls";// 设置要导出的文件的名字
		int rowNum = 1;
		String[] headers = { "序号", "姓名", "性别", "部门", "职务", "手机号", "是否党员", "入党日期" };
		// headers表示excel表中第一行的表头
		HSSFRow row = sheet.createRow(0);

		for (int i = 0; i < headers.length; i++) {
			HSSFCell cell = row.createCell(i);
			HSSFRichTextString text = new HSSFRichTextString(headers[i]);
			cell.setCellValue(text);
		}
		if (!XTListUtils.isEmpty(list.getDataList())) {
			// 在表中存放查询到的数据放入对应的列
			for (SysUserVO v : list.getDataList()) {
				HSSFRow row1 = sheet.createRow(rowNum);
				row1.createCell(0).setCellValue(rowNum);
				row1.createCell(1).setCellValue(v.getNickname());
				row1.createCell(2).setCellValue(v.getUserExtendEO().getSex());
				row1.createCell(3).setCellValue(v.getDeptUser().getDeptName());
				row1.createCell(4).setCellValue(v.getUserExtendEO().getPosition());
				row1.createCell(5).setCellValue(v.getPhone());
				row1.createCell(6).setCellValue(v.getUserExtendEO().getIsParty());
				if (v.getUserExtendEO().getJoinPartyDate() == null) {
					row1.createCell(7).setCellValue("");
				} else {
					sdf = new SimpleDateFormat("yyyy-MM-dd");
					row1.createCell(7).setCellValue(sdf.format(v.getUserExtendEO().getJoinPartyDate()));
				}
				rowNum++;
			}
		}
		response.setContentType("application/octet-stream");
		response.setHeader("Content-disposition",
				"attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
		response.flushBuffer();
		workbook.write(response.getOutputStream());
	}
	

	
	/**
	 * 下载模版
	 * @param res
	 * @throws IOException
	 */
	@RequestMapping(value = "downloadExecl", method = RequestMethod.GET)
	public void downloadExecl(HttpServletResponse res) throws IOException {
		String fileName = "工作人员信息表.xlsx";
		 fileName = new String(fileName.getBytes("GB2312"), "ISO_8859_1"); 
		res.setContentType("application/x-download");
		res.addHeader("Content-Disposition", "attachment;fileName=" + fileName);   // 设置文件名
		res.setHeader("content-type", "application/octet-stream");
		byte[] buff = new byte[1024];
		BufferedInputStream bis = null;
		OutputStream os = null;
		try {
			File cfgFile = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "static/excel/workuser.xlsx");
			os = res.getOutputStream();
			bis = new BufferedInputStream(new FileInputStream(cfgFile));
			int i = bis.read(buff);
			while (i != -1) {
				os.write(buff, 0, buff.length);
				os.flush();
				i = bis.read(buff);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	
	/**
	 * 导入
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	@ResponseBody
	public AjaxResult uploadExcel(HttpServletRequest request) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		InputStream inputStream = null;
		MultipartFile file = multipartRequest.getFile("filename");
		if (file.isEmpty()) {
			return AjaxResult.getResult(Boolean.FALSE, "文件不能为空");
		}
		try {
			inputStream = file.getInputStream();
			userExtendService.importUserList(file);
			inputStream.close();	
		} catch (Exception e) {
			e.printStackTrace();
		   return AjaxResult.getResult(Boolean.FALSE, e.getMessage());
		}catch (XTBusinessException e) {
			e.printStackTrace();
			return AjaxResult.getResult(Boolean.FALSE, e.getMessage());
		}
		return AjaxResult.getResult(Boolean.TRUE, "上传成功");
	}
	
	
	
}
